extends Area2D
class_name Experience

signal collected(value)

@export var value: int = 1  # 经验值大小
@export var move_speed: float = 150.0  # 向玩家移动的速度
@export var pickup_effect: PackedScene = null  # 拾取特效

var player: Node2D = null
var velocity: Vector2 = Vector2.ZERO
var is_attracted: bool = false  # 是否被玩家吸引

func _ready():
	# 连接碰撞信号
	connect("body_entered", _on_body_entered)
	
	# 找到玩家
	player = get_node_or_null("/root/Main/World/Player")

func _physics_process(delta):
	if player == null:
		return
	
	# 计算到玩家的距离
	var distance = global_position.distance_to(player.global_position)
	
	# 获取玩家的拾取半径
	var pickup_radius = player.pickup_radius if player.has_method("get_pickup_radius") or "pickup_radius" in player else 100.0
	
	# 如果在吸引范围内或已经被吸引，向玩家移动
	if is_attracted or distance < pickup_radius:
		is_attracted = true
		var direction = (player.global_position - global_position).normalized()
		velocity = direction * move_speed
		
		# 随着接近玩家速度加快
		var speed_modifier = 1.0 + (1.0 - min(distance / pickup_radius, 1.0))
		velocity *= speed_modifier
		
		# 移动经验宝石
		global_position += velocity * delta

func _on_body_entered(body):
	if body.is_in_group("player") or body.name == "Player":
		# 触发收集信号
		collected.emit(value)
		
		# 播放拾取特效（如果有）
		#if pickup_effect:
			#var effect = pickup_effect.instantiate()
			#effect.global_position = global_position
			#get_parent().add_child(effect)
		
		# 移除宝石
		queue_free()

# 设置经验值
func set_experience_value(exp_value: int):
	value = exp_value 
